package com.hyd.hx_adr.modules.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyd.hx_adr.domain.entity.JsonResult;
import com.hyd.hx_adr.exception.BusinessException;
import com.hyd.hx_adr.modules.common.domain.info.SmsCodeInfo;
import com.hyd.hx_adr.modules.common.service.CommonService;
import com.hyd.hx_adr.modules.user.domain.entity.User;
import com.hyd.hx_adr.modules.user.mapper.UserMapper;
import com.hyd.hx_adr.modules.user.service.UserService;
import com.hyd.hx_adr.utils.RedisUtils;
import com.hyd.hx_adr.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserService userService;

    @Override
    public JsonResult<String> getSmsCode(SmsCodeInfo info) {

        if (!redisUtils.hasKey(info.getCodeId() + "_VERIFY_CODE")) {
            throw new BusinessException("验证码已过期");
        }

        String c = redisUtils.get(info.getCodeId() + "_VERIFY_CODE").toString();
        if (!c.equalsIgnoreCase(info.getCode()))
            throw new BusinessException("验证码错误");

        User user = userService.lambdaQuery().eq(User::getPhone, info.getPhone()).one();
        if (user != null)
            return ResultUtils.error("手机号已被其他用户使用");

        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }

        // 十分钟内有效
        redisTemplate.opsForValue().set(info.getPhone() + sb, sb.toString(), 10, TimeUnit.MINUTES);
        redisUtils.del(info.getCodeId() + "_VERIFY_CODE");
        return ResultUtils.success(sb.toString());
    }
}
